import * as express from 'express';
import * as http from 'http';
import * as https from 'https';
import * as qs from 'querystring';

declare global{
    interface String{
        format(...args: any[]):string;
    }
}


String.prototype.format = function(...args){
    let result = <string>this;
    if(args.length > 0){
        if(args.length == 1 && typeof args[0] == 'object'){
            for(let key in args){
                if(args[key] != undefined){
                    let reg = new RegExp('({' + key + '})', 'g');
                    result = result.replace(reg, args[key]);
                }
            }
        }
        else{
            for(let i = 0; i < args.length; i++){
                if(args[i] != undefined){
                    let reg = new RegExp('({)' + i + '(})', 'g');
                    result = result.replace(reg, args[i]);
                }
            }
        }
    }
    console.log(result);
    return result;
};


export default class Http{
    static send(res: express.Response, errcode: number, errmsg?: string, data?:ret){
        if(data == null){
            data = <d>{};
        }
        data.errcode = errcode;
        data.errmsg = errmsg;
        res.send(JSON.stringify(data));
    }

    static get(host, port, path, data:ret, callback:(ret:boolean, data:ret)=>void, safe?){
        const content = qs.stringify(data);
        const options:http.RequestOptions = {
            hostname: host,
            path: path + '?' + content,
            method: 'GET'
        };
        if(port){
            options.port = port;
        }
        let proto:typeof http | typeof https = http;
        if(safe){
            proto = https;
        }

        const req = (<typeof http>proto).request(options, res => {
            res.setEncoding('utf8');
            res.on('data', chunk => {
                const json = JSON.parse(chunk + '');
                callback(true, json);
            });
        });

        req.on('error', e => {
            console.log('请求数据发生错误，错误信息：' + e.message);
            callback(false, e);
        });

        req.end();
    }
}


interface d{
    errcode;
    errmsg;
}


